<?php
// public/reports/personnel.php
declare(strict_types=1);
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/layout.php';
require_once __DIR__ . '/../../includes/flash.php';

require_login();
$user = current_user();

// Only admin/hr can view reports
if (!in_array($user['role'], ['admin','hr'], true)) {
    set_flash('danger', 'You are not authorized to access reports.');
    header('Location: /ldp/public/dashboard.php');
    exit;
}

global $pdo;

$q       = trim($_GET['search'] ?? '');
$year    = trim($_GET['year'] ?? '');

$params = [];
$where  = [];

// keyword search
if ($q !== '') {
    $where[] = "(employee_id LIKE :q1
              OR name LIKE :q2
              OR position LIKE :q3
              OR employee_type LIKE :q4
              OR status LIKE :q5
              OR address LIKE :q6
              OR cpnumber LIKE :q7
              OR type LIKE :q8
              OR level LIKE :q9)";
    $params = array_merge($params, [
        ':q1' => "%$q%",
        ':q2' => "%$q%",
        ':q3' => "%$q%",
        ':q4' => "%$q%",
        ':q5' => "%$q%",
        ':q6' => "%$q%",
        ':q7' => "%$q%",
        ':q8' => "%$q%",
        ':q9' => "%$q%",
    ]);
}


$sql = "SELECT * FROM training";
if ($where) {
    $sql .= " WHERE " . implode(" AND ", $where);
}
$sql .= " ORDER BY updated_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();


render_header('Training Report', 'reports');
$flash = get_flash();
if ($flash): ?>

<style>
 @media print {
          .btn-print {
            display:none !important;
          }
		  .card2 {
			  display:none !important;
		  }
		  .btn-danger {
			   display:none !important;
		  }
		  .met {
			  display:none !important;
		  }
		  .mr-2 {
			  display:none !important;
		  }
      }

  
</style>

  <div class="alert alert-<?= htmlspecialchars($flash['type'] ?? '') ?>">
    <?= htmlspecialchars($flash['message'] ?? '') ?>
  </div>
<?php endif; ?>

<div class="card">
  
  
<form method="POST" class="met">
      <div class="input-group mr-2">
      <input type="text" id="searchInput" style="width:400px;font-size:18px;" onkeyup="myFunction()" placeholder="">
       <input type="text" id="searchInput" style="width:90px;font-size:18px;" onkeyup="myFunction()" placeholder="">
      
	  </div>

     
      <div class="input-group-append">
        <button type="submit" class="btn btn-outline-secondary"><i class="fas fa-search">Click to Search</i></button>
        <a href="personnel.php" class="btn btn-outline-dark">Reset</a>
      </div>
    </form>

    <!-- Export buttons -->
    <div class="ml-2">
      <?php
      // keep same filters in export links
      $query = http_build_query([
        'search' => $q,
      ]);
      ?>
      <a href="export_personnel.php?format=pdf&<?= $query ?>" class="btn btn-sm btn-danger"><i class="fas fa-file-pdf"></i> Export PDF</a>
      <!--<a href="export_personnel.php?format=excel&<?= $query ?>" class="btn btn-sm btn-success"><i class="fas fa-file-excel"></i> Export Excel</a> -->
    
	</div>
   <a class = "btn btn-success btn-print" href = "" onclick = "window.print()"><i class ="glyphicon glyphicon-print"></i> Print</a>
	

  <div class="card-body p-0">
    <div class="table-responsive">
	<br></br>
	<table class="header">
    <tr>
        <td><img src="http://localhost/ldp/public/assets/img/logo.png" alt="Logo" style="width:90px;height:90px;border-raduis:50%;" class="brand-image img-circle elevation-3"></td>
        <td style="width: 70%;">
            Republic of the Philippines<br>
            <strong>DR. EMILIO B. ESPINOSA SR., MEMORIAL STATE COLLEGE OF AGRICULTURE AND TECHNOLOGY</strong><br>
            Cabitan, Mandaon, Masbate | <a href="http://www.debesmscat.edu.ph">www.debesmscat.edu.ph</a><br>
            <strong style="font-size:23px;">TRAINING REPORTS</strong>
        </td>
        
        <td style="width: 15%;">
            
            <img src="http://localhost/ldp/public/assets/img/l.png" alt="mylogo" style="width:90px;height:90px;">
        </td>
    </tr>
</table>
	
	
      <table class="table table-striped mb-0" id="myTable">
        <thead>
          <tr>
         
            <th>Training Title of L&D </th>
            <th>Training Description</th>
            <th>Category</th>
            <th>Type of L&D</th>
			<th>Training Schedule From</th>
			 <th>Training Schedule Date</th>
            
          </tr>
        </thead>
        <tbody>

          <?php if (!$rows): ?>
            <tr><td colspan="10" class="text-center text-muted p-4">No Training records found.</td></tr>
          <?php else: foreach ($rows as $p): 
		  $babykop=$p['id']?? null;
		  
		  ?>
            <tr>
             
              <td><?= htmlspecialchars($p['title'] ?? '') ?></td>
              <td><?= htmlspecialchars($p['description'] ?? '') ?></td>
              <td>
                <?php if (!empty($p['leveloftraining'])): ?>
                  <span class="badge badge-info"><?= htmlspecialchars($p['leveloftraining']) ?></span>
                <?php endif; ?>
              </td>
              <td>
               <?php if (!empty($p['lnd'])): ?>
                  <span ><?= htmlspecialchars($p['lnd']) ?></span>
                <?php endif; ?>
                  
              </td>
			   <td>
               <?php if (!empty($p['date_from'])): ?>
                  <span ><?= htmlspecialchars($p['date_from']) ?></span>
                <?php endif; ?>
                  
              </td>
			  <td>
               <?php if (!empty($p['created_at'])): ?>
                  <span ><?= htmlspecialchars($p['created_at']) ?></span>
                <?php endif; ?>
                  
              </td>
			  <?php
			  $con = mysqli_connect("localhost","root","","ldp_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  date_default_timezone_set("Asia/Manila"); 
			    	$query=mysqli_query($con,"select * from training where traineename='$babykop'")or die(mysqli_error($con));
		$row56=mysqli_fetch_array($query);
			  
			  ?>
			  
			  
			  
			  
              <!-- <td><?= htmlspecialchars($p['address'] ?? '') ?></td>
              <td><?= htmlspecialchars($p['cpnumber'] ?? '') ?></td>
              <td>
                <?php if (!empty($p['date_from']) && !empty($p['date_to'])): ?>
                  <?= htmlspecialchars($p['date_from']) ?> to <?= htmlspecialchars($p['date_to']) ?>
                <?php else: ?>
                  <?= htmlspecialchars($p['updated_at'] ?? '') ?>
                <?php endif; ?>
              </td>
              <td><?= htmlspecialchars($p['traineetype'] ?? '') ?></td>
              <td><?= htmlspecialchars($p['level'] ?? '') ?></td> -->
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
  <script>
    document.getElementById('searchInput').addEventListener('keyup', function() {
      const filter = this.value.toUpperCase();
      const table = document.getElementById('myTable');
      const rows = table.getElementsByTagName('tr');

      for (let i = 1; i < rows.length; i++) { // Skip the header row
        const cells = rows[i].getElementsByTagName('td');
        let match = false;

        for (let j = 0; j < cells.length; j++) {
          if (cells[j]) {
            const text = cells[j].textContent || cells[j].innerText;
            if (text.toUpperCase().indexOf(filter) > -1) {
              match = true;
              break;
            }
          }
        }

        rows[i].style.display = match ? '' : 'none';
      }
    });
  </script>

<?php render_footer(); ?>
